<template>
  <div class="password-generator-tool">
    <div class="tool-header">
      <h1>随机密码生成工具</h1>
      <p>快速生成安全可靠的随机密码</p>
    </div>

    <div class="tool-container">
      <el-row :gutter="20">
        <!-- 配置区域 -->
        <el-col :span="12">
          <div class="config-section">
            <div class="section-header">
              <h3>密码配置</h3>
            </div>
            
            <div class="config-options">
              <div class="option-group">
                <label>密码长度：</label>
                <el-slider
                  v-model="passwordLength"
                  :min="4"
                  :max="128"
                  :step="1"
                  show-input
                  :show-input-controls="false"
                />
              </div>
              
              <div class="option-group">
                <label>包含字符类型：</label>
                <el-checkbox-group v-model="characterTypes">
                  <el-checkbox label="uppercase">大写字母 (A-Z)</el-checkbox>
                  <el-checkbox label="lowercase">小写字母 (a-z)</el-checkbox>
                  <el-checkbox label="numbers">数字 (0-9)</el-checkbox>
                  <el-checkbox label="symbols">特殊符号 (!@#$%^&*)</el-checkbox>
                </el-checkbox-group>
              </div>
              
              <div class="option-group">
                <label>排除字符：</label>
                <el-input
                  v-model="excludeChars"
                  placeholder="输入要排除的字符，如：0O1lI"
                />
              </div>
              
              <div class="option-group">
                <label>生成数量：</label>
                <el-input-number
                  v-model="passwordCount"
                  :min="1"
                  :max="50"
                  controls-position="right"
                />
              </div>
            </div>
            
            <div class="generate-actions">
              <el-button 
                type="primary" 
                @click="generatePasswords"
                :disabled="!hasValidConfig"
                :loading="isGenerating"
                size="large"
              >
                <el-icon><Refresh /></el-icon>
                生成密码
              </el-button>
              <el-button @click="clearAll" size="large">清空</el-button>
            </div>
          </div>
        </el-col>

        <!-- 结果区域 -->
        <el-col :span="12">
          <div class="result-section">
            <div class="section-header">
              <h3>生成的密码</h3>
              <div class="actions">
                <el-button @click="copyAllPasswords" size="small" :disabled="!passwords.length">复制全部</el-button>
                <el-button @click="clearPasswords" size="small">清空</el-button>
              </div>
            </div>
            
            <div class="passwords-container">
              <div 
                v-for="(password, index) in passwords" 
                :key="index"
                class="password-item"
              >
                <div class="password-info">
                  <span class="password-number">{{ index + 1 }}</span>
                  <span class="password-strength" :class="getStrengthClass(password)">
                    {{ getPasswordStrength(password) }}
                  </span>
                </div>
                <div class="password-content">
                  <el-input
                    :model-value="password"
                    readonly
                    class="password-input"
                  />
                  <el-button @click="copyPassword(password)" size="small">复制</el-button>
                </div>
              </div>
            </div>
            
            <div class="password-stats" v-if="passwords.length">
              <el-tag type="info" size="small">
                已生成 {{ passwords.length }} 个密码
              </el-tag>
              <el-tag type="success" size="small">
                平均强度: {{ averageStrength }}
              </el-tag>
            </div>
          </div>
        </el-col>
      </el-row>

      <!-- 密码强度说明 -->
      <div class="strength-info">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>密码强度说明</span>
            </div>
          </template>
          
          <div class="strength-content">
            <div class="strength-levels">
              <div class="strength-item weak">
                <span class="strength-label">弱</span>
                <span class="strength-desc">长度小于8位或字符类型单一</span>
              </div>
              <div class="strength-item medium">
                <span class="strength-label">中等</span>
                <span class="strength-desc">8-12位，包含2-3种字符类型</span>
              </div>
              <div class="strength-item strong">
                <span class="strength-label">强</span>
                <span class="strength-desc">12位以上，包含3-4种字符类型</span>
              </div>
              <div class="strength-item very-strong">
                <span class="strength-label">很强</span>
                <span class="strength-desc">16位以上，包含4种字符类型</span>
              </div>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 使用说明 -->
      <div class="tool-info">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>使用说明</span>
            </div>
          </template>
          
          <div class="info-content">
            <h4>密码生成建议：</h4>
            <ul>
              <li>使用至少12位长度的密码</li>
              <li>包含大小写字母、数字和特殊符号</li>
              <li>避免使用常见词汇和模式</li>
              <li>定期更换密码</li>
              <li>为不同账户使用不同密码</li>
            </ul>
            
            <h4>安全提示：</h4>
            <div class="warning">
              <p>⚠️ 请妥善保管生成的密码，建议使用密码管理器存储</p>
              <p>⚠️ 不要在公共场所或不安全的网络环境下生成密码</p>
              <p>⚠️ 生成的密码仅在前端处理，不会上传到服务器</p>
            </div>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Refresh } from '@element-plus/icons-vue'

const passwordLength = ref(12)
const characterTypes = ref(['uppercase', 'lowercase', 'numbers', 'symbols'])
const excludeChars = ref('')
const passwordCount = ref(5)
const passwords = ref([])
const isGenerating = ref(false)

const hasValidConfig = computed(() => {
  return characterTypes.value.length > 0 && passwordLength.value > 0
})

const averageStrength = computed(() => {
  if (passwords.value.length === 0) return '无'
  
  const strengths = passwords.value.map(pwd => getPasswordStrength(pwd))
  const strongCount = strengths.filter(s => s === '强' || s === '很强').length
  const percentage = Math.round((strongCount / passwords.value.length) * 100)
  return `${percentage}% 强密码`
})

const generatePasswords = async () => {
  if (!hasValidConfig.value) {
    ElMessage.warning('请至少选择一种字符类型')
    return
  }
  
  isGenerating.value = true
  try {
    // 模拟处理延迟
    await new Promise(resolve => setTimeout(resolve, 500))
    
    const newPasswords = []
    const charset = buildCharacterSet()
    
    if (charset.length === 0) {
      ElMessage.error('字符集为空，请检查配置')
      return
    }
    
    for (let i = 0; i < passwordCount.value; i++) {
      let password = ''
      for (let j = 0; j < passwordLength.value; j++) {
        const randomIndex = Math.floor(Math.random() * charset.length)
        password += charset[randomIndex]
      }
      newPasswords.push(password)
    }
    
    passwords.value = newPasswords
    ElMessage.success(`已生成 ${passwordCount.value} 个密码`)
  } catch (error) {
    ElMessage.error('生成失败：' + error.message)
  } finally {
    isGenerating.value = false
  }
}

const buildCharacterSet = () => {
  let charset = ''
  
  if (characterTypes.value.includes('uppercase')) {
    charset += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
  }
  if (characterTypes.value.includes('lowercase')) {
    charset += 'abcdefghijklmnopqrstuvwxyz'
  }
  if (characterTypes.value.includes('numbers')) {
    charset += '0123456789'
  }
  if (characterTypes.value.includes('symbols')) {
    charset += '!@#$%^&*()_+-=[]{}|;:,.<>?'
  }
  
  // 排除指定字符
  if (excludeChars.value) {
    for (const char of excludeChars.value) {
      charset = charset.replace(new RegExp(char, 'g'), '')
    }
  }
  
  return charset
}

const getPasswordStrength = (password) => {
  const length = password.length
  let typeCount = 0
  
  if (/[a-z]/.test(password)) typeCount++
  if (/[A-Z]/.test(password)) typeCount++
  if (/[0-9]/.test(password)) typeCount++
  if (/[^a-zA-Z0-9]/.test(password)) typeCount++
  
  if (length < 8 || typeCount < 2) return '弱'
  if (length < 12 || typeCount < 3) return '中等'
  if (length < 16 || typeCount < 4) return '强'
  return '很强'
}

const getStrengthClass = (password) => {
  const strength = getPasswordStrength(password)
  return {
    'weak': strength === '弱',
    'medium': strength === '中等',
    'strong': strength === '强',
    'very-strong': strength === '很强'
  }
}

const copyPassword = async (password) => {
  try {
    await navigator.clipboard.writeText(password)
    ElMessage.success('密码已复制到剪贴板')
  } catch (error) {
    // 降级方案
    const textArea = document.createElement('textarea')
    textArea.value = password
    document.body.appendChild(textArea)
    textArea.select()
    document.execCommand('copy')
    document.body.removeChild(textArea)
    ElMessage.success('密码已复制到剪贴板')
  }
}

const copyAllPasswords = async () => {
  if (passwords.value.length === 0) {
    ElMessage.warning('没有可复制的密码')
    return
  }
  
  const allPasswords = passwords.value.join('\n')
  try {
    await navigator.clipboard.writeText(allPasswords)
    ElMessage.success('所有密码已复制到剪贴板')
  } catch (error) {
    ElMessage.error('复制失败')
  }
}

const clearPasswords = () => {
  passwords.value = []
  ElMessage.info('已清空密码列表')
}

const clearAll = () => {
  passwords.value = []
  passwordLength.value = 12
  characterTypes.value = ['uppercase', 'lowercase', 'numbers', 'symbols']
  excludeChars.value = ''
  passwordCount.value = 5
  ElMessage.info('已重置所有配置')
}
</script>

<style scoped>
.password-generator-tool {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.tool-header {
  text-align: center;
  margin-bottom: 40px;
}

.tool-header h1 {
  font-size: 2.5rem;
  color: #333;
  margin-bottom: 10px;
}

.tool-header p {
  color: #666;
  font-size: 1.1rem;
}

.tool-container {
  margin-bottom: 40px;
}

.config-section,
.result-section {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  border: 1px solid #f0f0f0;
  height: 100%;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-header h3 {
  color: #333;
  margin: 0;
  font-size: 1.3rem;
}

.actions {
  display: flex;
  gap: 8px;
}

.config-options {
  margin-bottom: 30px;
}

.option-group {
  margin-bottom: 20px;
}

.option-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #333;
}

.generate-actions {
  display: flex;
  gap: 12px;
  margin-top: 30px;
}

.passwords-container {
  max-height: 400px;
  overflow-y: auto;
  margin-bottom: 20px;
}

.password-item {
  margin-bottom: 15px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.password-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.password-number {
  font-weight: bold;
  color: #667eea;
}

.password-strength {
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 0.8rem;
  font-weight: bold;
}

.password-strength.weak {
  background: #f8d7da;
  color: #721c24;
}

.password-strength.medium {
  background: #fff3cd;
  color: #856404;
}

.password-strength.strong {
  background: #d1ecf1;
  color: #0c5460;
}

.password-strength.very-strong {
  background: #d4edda;
  color: #155724;
}

.password-content {
  display: flex;
  gap: 8px;
  align-items: center;
}

.password-input {
  flex: 1;
}

.password-stats {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.strength-info,
.tool-info {
  margin-top: 40px;
}

.card-header {
  font-weight: bold;
  color: #333;
}

.strength-levels {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 15px;
}

.strength-item {
  display: flex;
  flex-direction: column;
  padding: 15px;
  border-radius: 8px;
  border: 2px solid;
}

.strength-item.weak {
  border-color: #dc3545;
  background: #f8d7da;
}

.strength-item.medium {
  border-color: #ffc107;
  background: #fff3cd;
}

.strength-item.strong {
  border-color: #17a2b8;
  background: #d1ecf1;
}

.strength-item.very-strong {
  border-color: #28a745;
  background: #d4edda;
}

.strength-label {
  font-weight: bold;
  font-size: 1.1rem;
  margin-bottom: 5px;
}

.strength-desc {
  font-size: 0.9rem;
  color: #666;
}

.info-content h4 {
  color: #333;
  margin: 20px 0 10px 0;
  font-size: 1.1rem;
}

.info-content ul {
  color: #666;
  padding-left: 20px;
  margin-bottom: 15px;
}

.info-content li {
  margin-bottom: 5px;
}

.warning {
  background: #fff3cd;
  padding: 15px;
  border-radius: 8px;
  border-left: 4px solid #ffc107;
  margin: 15px 0;
}

.warning p {
  margin: 5px 0;
  color: #856404;
}

@media (max-width: 768px) {
  .tool-header h1 {
    font-size: 2rem;
  }
  
  .section-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .generate-actions {
    flex-direction: column;
  }
  
  .password-content {
    flex-direction: column;
    align-items: stretch;
  }
  
  .strength-levels {
    grid-template-columns: 1fr;
  }
}
</style>